import Page from '@/components/Page';
import Title from '@/components/Title';
import { pipInstall, python } from '@/utils/api';
import ProCard from '@ant-design/pro-card';
import { open } from '@tauri-apps/api/dialog';
import { Button, Empty, Input, List, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useLocalStorageState, useReactive } from 'ahooks';


function Demo() {
  const [names, setNames] = useState('');
  const [values, setValues] = useLocalStorageState<any[]>('pip_list', []);
  const state = useReactive({
    stream: [] as string[],
    modules: values as string[],
  });
  useEffect(() => {
    python({
      program: 'pip',
      args: ['list', '--format', 'freeze'],
      callback: (line: string) => {
        if (line.includes('==') && values.length > 0) {
          state.modules.push(line);
        }
      },
    }).then((items: any) => {
      setValues(items);
    });
  }, []);

  const handleClick = async () => {
    const files = (await open({ multiple: true })) ?? [];
    console.log(files);
    for (let file of files) {
      try {
        const res = await pipInstall(file, (line) => {
          state.stream.push(line);
        });
        console.log(res);
        message.info('安装成功！');
      } catch (error) {
        message.error('安装失败！');
        console.error(error);
      }
    }
  };
  return (
    <Page title="安装Python包">
      <ProCard colSpan="100%" size="small" bodyStyle={{ padding: 0 }}>
        <Input.Group compact style={{ display: 'flex' }}>
          <Input
            placeholder="flask,click,pandas..."
            onChange={(e) => setNames(e.target.value)}
          />
          <Button
            type="primary"
            onClick={async () => {
              for (let name of names.split(',')) {
                try {
                  const res = await pipInstall(name.trim(), (line) => {
                    state.stream.push(line);
                  });
                  console.log(res);
                  message.info('安装成功！');
                } catch (error) {
                  message.error('安装失败！');
                  console.error(error);
                }
              }
            }}
          >
            安装
          </Button>
          <Button style={{ marginLeft: 5 }} onClick={handleClick}>
            从whl安装
          </Button>
        </Input.Group>
      </ProCard>
      <ProCard
        bodyStyle={{ padding: '8px 0', maxHeight: 'calc(100vh - 180px)' }}
      >
        <ProCard
          headerBordered
          bordered
          title={<Title level={3}>已安装</Title>}
          colSpan="240px"
          size="small"
          // headStyle={{ height: 40 }}
          bodyStyle={{ overflow: 'auto', maxHeight: 'calc(100vh - 180px)' }}
        >
          <List
            size="small"
            itemLayout="horizontal"
            dataSource={values}
            renderItem={(item) => <List.Item>{item}</List.Item>}
          />
        </ProCard>
        <pre
          className="logging"
          style={{ maxHeight: 'calc(100vh - 160px)', overflow: 'auto' }}
        >
          {[...state.stream].map((line: string, i: number) => (
            <code key={i}>{line}</code>
          ))}
        </pre>

        <ProCard
          title={<Title level={3}>安装日志</Title>}
          size="small"
          headerBordered
          bordered
          bodyStyle={{
            maxHeight: 'calc(100vh - 180px)',
            maxWidth: 'calc(100vw - 330px)',
            padding: 0,
          }}
        >
          {state.stream?.length > 0 ? null : <Empty />}
          <pre
            className="logging"
            style={{
              margin: 0,
              maxHeight: 'calc(100vh - 180px)',
              maxWidth: 'calc(100vw - 330px)',
              overflow: 'auto',
              padding: '12px',
            }}
          >
            {state.stream?.map((line: string, i: number) => (
              <code key={i}>{line}</code>
            ))}
          </pre>
        </ProCard>
      </ProCard>
    </Page>
  );
}

export default Demo;
